<template>
  <a-modal
    v-model:visible="showComputed"
    width="888px"
    title="Create New Code"
    wrap-class-name="primary-modal unlimited-height"
    ok-text="Create"
    :footer="showFooter"
    :ok-button-props="{ disabled: !buttonAvailable }"
    :destroy-on-close="true"
    @cancel="showComputed = false"
    @ok="handleGenerateContractNumber"
  >
    <div v-if="code === ''">
      <div style="padding-bottom: 24px">
        <a-alert>
          <template #message>
            1. If non-PRC clients, multilingual projects, sign with US/EU/SEA based on majority language pairs.<br />
            2. If non-PRC clients, simplified chinese projects, sign with project management entity.<br />
            3. If PRC clients, sign with project management entity.<br />
            4. In case of insurance requirements, non-PRC clients sign with US / PRC clients sign with Beijing.
          </template>
        </a-alert>
      </div>
      <a-form ref="createFormRef" layout="vertical" :rules="createFormRules" :model="createForm">
        <a-row :gutter="gutter">
          <a-col :span="12">
            <a-form-item label="Document Branch" name="documentBranch">
              <a-select
                v-model:value="createForm.documentBranch"
                show-search
                allow-clear
                option-filter-prop="label"
                option-label-prop="label"
                placeholder="Please select"
              >
                <a-select-option v-for="item in companies" :key="item.value" :label="item.text + item.nameEN">
                  <a-space>
                    {{ item.text }}
                    <span v-if="item.text !== item.nameEN" style="color: #bfbfbf">
                      {{ item.nameEN }}
                    </span>
                  </a-space>
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="Document BU" name="documentBU">
              <a-select
                v-model:value="createForm.documentBU"
                show-search
                allow-clear
                option-filter-prop="label"
                option-label-prop="label"
                placeholder="Please select"
              >
                <a-select-option v-for="item in documentBUDict" :key="item.value" :label="item.text">
                  {{ item.text }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter="gutter">
          <a-col :span="12">
            <a-form-item label="Document Matters" name="documentMatters">
              <a-select
                v-model:value="createForm.documentMatters"
                disabled
                show-search
                allow-clear
                option-filter-prop="label"
                option-label-prop="label"
                placeholder="Please select"
              >
                <a-select-option v-for="item in documentMattersDict" :key="item.value" :label="item.text">
                  {{ item.text }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="Document Category" name="documentCategory">
              <a-select
                v-model:value="createForm.documentCategory"
                show-search
                allow-clear
                option-filter-prop="label"
                option-label-prop="label"
                placeholder="Please select"
              >
                <a-select-option v-for="item in documentCategory" :key="item.value" :label="item.text">
                  {{ item.text }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter="gutter">
          <a-col :span="24">
            <a-form-item label="Date Of Signing" name="dateOfSigning">
              <a-date-picker
                v-model:value="createForm.dateOfSigning"
                format="YYYY-MM-DD"
                value-format="YYMMDD"
                allow-clear
              />
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter="gutter">
          <a-col :span="24">
            <a-form-item label="Document Confidentiality Level" name="documentConfidentialityLevel">
              <a-select
                v-model:value="createForm.documentConfidentialityLevel"
                show-search
                option-filter-prop="label"
                option-label-prop="label"
                placeholder="Please select"
              >
                <a-select-option v-for="item in documentConfidentialityLevelDict" :key="item.value" :label="item.text">
                  {{ item.text }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
      <a-alert v-if="createForm.documentConfidentialityLevel" type="warning">
        <template #message>
          <div v-html="documentConfidentialityLevelDict[createForm.documentConfidentialityLevel - 1].tips" />
        </template>
      </a-alert>
    </div>
    <div v-else>
      <a-result status="success" :title="'Contract Number: ' + code">
        <template #extra>
          <a-button key="console" class="copy-btn" type="primary" @click="copy(code)">Copy</a-button>
        </template>
      </a-result>
    </div>
  </a-modal>
</template>

<script setup>
import { computed, watch, inject, reactive, ref } from 'vue'
import { useStore } from 'vuex'
import Contract from '@/api/client/contract.js'
import ClipboardJS from 'clipboard'
import { OPERATION_SUCCESSFUL } from '@/constants/message.js'
const { message } = inject('Feedback')
const props = defineProps({
  show: Boolean,
  clientId: [Number, String],
  autoInject: {
    type: Boolean,
    default: false
  }
})
const store = useStore()
const dict = ref(computed(() => store.state.dict))
const companies = ref([])
const emits = defineEmits(['update:show', 'inject'])
const showComputed = computed({
  get: () => props.show,
  set: val => emits('update:show', val)
})
// Create New Code
const code = ref('')
const copy = text => {
  const clipboard = new ClipboardJS('.copy-btn', {
    text: () => {
      return text
    }
  })
  clipboard.on('success', () => {
    message.success('Copied !')
    clipboard.destroy()
  })
  clipboard.on('error', () => {
    message.warning('Browser not support, Please copy manually.')
    clipboard.destroy()
  })
}
const showFooter = computed(() => {
  return code.value === '' ? undefined : null
})
const gutter = [24, 24]
const documentBUDict = [
  {
    text: 'Game L10N',
    value: 2
  },
  {
    text: 'Intelligent Manufacturing',
    value: 3
  },
  {
    text: 'ICT&Software',
    value: 4
  },
  {
    text: 'IT&Elearning',
    value: 5
  },
  {
    text: 'Financial law',
    value: 6
  },
  {
    text: 'Medicine',
    value: 7
  },
  {
    text: 'Medical Devices',
    value: 8
  },
  {
    text: 'Instrument',
    value: 9
  },
  {
    text: 'Patent',
    value: 10
  },
  {
    text: 'Data Annotation',
    value: 11
  },
  {
    text: '我译网事业部',
    value: 21
  }
]
const documentMattersDict = [
  {
    text: 'Management Documents',
    value: 1
  },
  {
    text: 'Technical Documents',
    value: 2
  },
  {
    text: 'Sales Contracts',
    value: 3
  },
  {
    text: 'Procurement contract',
    value: 4
  },
  {
    text: 'Training materials',
    value: 5
  },
  {
    text: 'Meeting',
    value: 6
  },
  {
    text: 'Other',
    value: 7
  }
]
const documentCategory = [
  {
    text: 'SOP',
    value: 1
  },
  {
    text: 'EXE file',
    value: 2
  },
  {
    text: 'Template',
    value: 3
  },
  {
    text: 'Form',
    value: 4
  }
]
const documentConfidentialityLevelDict = [
  {
    text: 'Top Secret Documents',
    value: 1,
    tips: '1. General ledger accounting information and related financial reports and statements.<br/>2. Salary distribution plan and related documents.<br/>3. Confidential matters in business strategic decisions and major decisions.<br/>4. Core technical information.<br/>5. Other documents and materials that should be classified as Top Secret (TS) documents.'
  },
  {
    text: 'Secret Document',
    value: 2,
    tips: '1. ERP system data and statements.<br/>2. Dev source code<br/>3. Reports and materials on project costs and profits.<br/>4. Other documents and materials that should be classified as secret documents.'
  },
  {
    text: 'Confidential Documents',
    value: 3,
    tips: "1. Information about clients and suppliers, clients' source documents, suppliers' achievements, etc.<br/>2. Various contracts and agreements.<br/>3. Management documents, record forms, etc. of project, development, procurement, HR, finance, and other professional departments.<br/>4. Labor contracts, employee personal information and attached documents.<br/>5. Other documents and materials that should be classified as confidential documents."
  },
  {
    text: 'General Documents',
    value: 4,
    tips: "1. General work rules and regulations.<br/>2. General notices and bulletins<br/>3. Routine approval documents.<br/>4. The company's samples, profile, etc."
  }
]
const createForm = reactive({
  documentBranch: null,
  documentBU: null,
  documentMatters: 3,
  documentCategory: null,
  dateOfSigning: null,
  documentConfidentialityLevel: 1
})
const createFormRef = ref(null)
const createFormRules = {
  documentBranch: [
    {
      required: true,
      message: 'Please Select',
      trigger: 'change'
    }
  ],
  documentBU: [
    {
      required: true,
      message: 'Please Select',
      trigger: 'change'
    }
  ],
  documentMatters: [
    {
      required: true,
      message: 'Please Select',
      trigger: 'change'
    }
  ],
  documentCategory: [
    {
      required: true,
      message: 'Please Select',
      trigger: 'change'
    }
  ],
  dateOfSigning: [
    {
      required: true,
      message: 'Please Select',
      trigger: 'change'
    }
  ],
  documentConfidentialityLevel: [
    {
      required: true,
      message: 'Please Select',
      trigger: 'change'
    }
  ]
}
const buttonAvailable = ref(true)
const handleGenerateContractNumber = () => {
  createFormRef.value.validate().then(() => {
    buttonAvailable.value = false
    Contract.generateContractNumber({
      clientId: parseInt(props.clientId),
      dBranch: createForm.documentBranch,
      dbu: createForm.documentBU,
      dItem: createForm.documentMatters,
      dCategory: createForm.documentCategory,
      date: parseInt(createForm.dateOfSigning),
      dcLevel: createForm.documentConfidentialityLevel
    })
      .then(res => {
        message.success(OPERATION_SUCCESSFUL)
        code.value = res.message
        if (props.autoInject) {
          showComputed.value = false
          emits('inject', res.message)
        }
      })
      .finally(() => {
        // showComputed.value = false
        buttonAvailable.value = true
      })
  })
}
watch(
  () => showComputed.value,
  value => {
    if (value) {
      createForm.documentBranch = null
      createForm.documentBU = null
      createForm.documentMatters = 3
      createForm.documentCategory = null
      createForm.dateOfSigning = null
      createForm.documentConfidentialityLevel = 1
      code.value = ''
    }
  }
)
store.dispatch('dict/getEciCompanies').then(() => {
  if (dict.value.eciCompanies.length > 0) {
    companies.value = [...companies.value, ...dict.value.eciCompanies]
  }
})
</script>

<style scoped></style>
